package tgc.edu.yzy.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import tgc.edu.yzy.entity.EimRole;
import tgc.edu.yzy.entity.EimRegister;
import tgc.edu.yzy.repostory.EimRegisterRepository;
import tgc.edu.yzy.security.User2;

@Service
public class CustomUserService implements UserDetailsService{

	@Autowired
	private EimRegisterRepository userDAO; 
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		SimpleDateFormat sd= new SimpleDateFormat("yyyy-MM-dd");
		EimRegister user = userDAO.findByUsername(username);
		if(user==null) {
			throw new UsernameNotFoundException(username);
		}
		//对用户授权时间进行判断
		//获取用户时间
		Date max = user.getMaxdate();//这里取出来的不可直接使用
		String dateNowStr = sd.format(max);
		Date dateNow1Str=null;
		try {
			dateNow1Str=sd.parse(dateNowStr);
		} catch (ParseException e) {
			throw new UsernameNotFoundException(username);
		}
		
		//获取计算机当前时间
		Date date=new Date();
		Calendar cal = Calendar.getInstance();//为了更友好，所以在结束当天也能使用
		cal.setTime(date);
		System.out.println(date+""+max);
		cal.add(Calendar.DATE, -1);
		if((cal.getTime()).before(dateNow1Str)||(dateNowStr).equals("1111-11-11")) {
			List<EimRole> roles = user.getRoles();
			List<GrantedAuthority> authorities=new ArrayList<>();
			for (EimRole role : roles) { 
				authorities.add(new SimpleGrantedAuthority(role.getCode()));
			}
			return new User2(user.getUsername(), user.getPassword(), user.getId(),user.getName(), authorities);
			
		}else {
			throw new UsernameNotFoundException(username);
			
		}
		
	}

}
